package cn.sunzq.sqlite.demo.config;


import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

//录入端配置
@Configuration
@MapperScan(basePackages =
        {"cn.sunzq.sqlite.demo.mapper.sqlite1"},
        sqlSessionFactoryRef = "sqlite1DataSqlSessionFactory")
public class SqlLite1DataSourceConfig {

    @Value("${spring.datasource.sqlite1.password:}")
    private String password;

    @Value("${spring.datasource.sqlite1.jdbc-url:jdbc:sqlite:./sqlitedemo/src/main/resources/sqlite}")
    private String url;

    @Value("${spring.datasource.sqlite1.driver-class-name:org.sqlite.JDBC}")
    private String driverClassName;

    @Value("${spring.datasource.sqlite1.username:}")
    private String username;

    @Autowired
    private HikariBaseConfig hikariBaseConfig;

    @Bean(name = "sqlite1DataDataSource")
    @Primary
    public DataSource landSysInDataDataSource(){
        return hikariBaseConfig.getDataSource(driverClassName, url, username, password);
    }

    @Bean(name = "sqlite1DataSqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("sqlite1DataDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean sessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:mapper/sqlite1/**/*.xml"));
        return sessionFactoryBean.getObject();
    }


    @Bean(name = "sqlite1DataSqlSessionProductTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlite1DataSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean(name = "sqlite1DataTransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("sqlite1DataDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
    @Bean
    @Primary
    public JdbcTemplate jdbcTemplate(@Qualifier("sqlite1DataDataSource") DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }

}